package controller

import (
	"context"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"user_bff/global"
	"user_bff/pkg"
	"user_bff/user_proto"
)

func UserLogin(c *gin.Context) {
	mobile := c.PostForm("mobile")
	password := c.PostForm("password")
	comment := pkg.Comment()
	byMobile, err := comment.GetUserByMobile(context.Background(), &user_proto.GetUserByMobileRequest{Mobile: mobile})
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	checkPassword, _ := comment.CheckPassword(context.Background(), &user_proto.CheckPasswordRequest{
		Password:          password,
		EncryptedPassword: byMobile.Password,
	})
	if !checkPassword.Success {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "密码错误",
			"data": nil,
		})
		return
	}
	marshal, _ := json.Marshal(byMobile)

	token, err := pkg.SetJwtToken(string(marshal), int64(global.ServerConfig.JwtConfig.AccessTokenExpireTime), int64(global.ServerConfig.JwtConfig.RefreshTokenExpireTime))
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "token生成失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "登录成功",
		"data": map[string]interface{}{
			"AccessToken":            token.AccessToken,
			"RefreshToken":           token.RefreshToken,
			"AccessTokenExpireTime":  global.ServerConfig.JwtConfig.AccessTokenExpireTime,
			"RefreshTokenExpireTime": global.ServerConfig.JwtConfig.RefreshTokenExpireTime,
		},
	})
	return
}

// 刷新令牌
func RefreshToken(c *gin.Context) {
	refreshToken := c.PostForm("refresh_token")
	token, err := pkg.RefreshJwtToken(refreshToken, 60)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "刷新令牌失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "刷新成功",
		"data": map[string]interface{}{
			"AccessToken":            token,
			"RefreshToken":           refreshToken,
			"AccessTokenExpireTime":  global.ServerConfig.JwtConfig.AccessTokenExpireTime,
			"RefreshTokenExpireTime": global.ServerConfig.JwtConfig.RefreshTokenExpireTime,
		},
	})
	return
}
